<template>
  <div v-loading="loading">
    <el-form ref="form" :model="form" :rules="rules" label-width="120px" class="dataForm">
      <el-row>
        <el-col :span="12">
          <el-form-item :label="$t('申请标题')" prop="actTitle">
            <el-input v-model="form.actTitle" :placeholder="$t('申请标题')" show-word-limit maxlength="50" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('申请人')" prop="applyUser">
            <UserSelect v-model="form.applyUser" :placeholder="$t('申请人')" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('申请时间')" prop="applyTime">
            <el-date-picker
              v-model="form.applyTime"
              clearable
              style="width: 200px"
              type="date"
              value-format="yyyy-MM-dd"
              :placeholder="$t('申请时间')"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('付款总金额') + $t('金额单位')" prop="total">
            <Money v-model="form.total" :placeholder="$t('付款总金额')" unit="w" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('币种')" prop="currency">
            <dictSelect
              v-model="form.currency"
              :clearable="true"
              dictionary="currency"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <!--收款方信息-->
      <div class="area-header">
        <span class="area-header-title">{{ $t('收款方信息') }}</span>
      </div>
      <el-row>
        <el-col :span="12">
          <el-form-item :label="$t('收款方名称')" prop="payeeName">
            <el-autocomplete
              v-model="form.payeeName"
              popper-class="my-autocomplete"
              :fetch-suggestions="querySearch"
              :placeholder="$t('收款方名称')"
              :maxlength="100"
              @select="handleSelect"
            >
              <i slot="suffix" class="el-icon-edit" @click="handleIconClick" />
              <template slot-scope="{ item }">
                <div class="name">{{ item.value }}</div>
                <span class="addr">{{ item.address }}</span>
              </template>
            </el-autocomplete>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('开户行名称')" prop="depositBank">
            <el-input v-model="form.depositBank" :placeholder="$t('开户行名称')" maxlength="100" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('账户名称')" prop="accountTitle">
            <el-input v-model="form.accountTitle" :placeholder="$t('账户名称')" maxlength="100" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('银行账号')" prop="bankNumber">
            <el-input v-model="form.bankNumber" :placeholder="$t('银行账号')" maxlength="100" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('收款方地址')" prop="addressReceiver">
            <el-input v-model="form.addressReceiver" :placeholder="$t('收款方地址')" maxlength="100" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item :label="$t('备注')" prop="remark">
            <el-input v-model="form.remark" type="textarea" :placeholder="$t('备注')" maxlength="1000" />
          </el-form-item>
        </el-col>
      </el-row>
      <div class="area-header">
        <span class="area-header-title">{{ $t('付款主体') }}</span>
      </div>
      <el-table
        :data="form.dealSecuritiesPaymentPayers"
        border
        class="nowrapTable formTable"
        :summary-method="getSummaries"
        show-summary
      >
        <el-table-column :label="$t('序号')" align="center" width="50">
          <template slot-scope="scope">
            {{ scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column :label="$t('主体名称')" align="center" min-width="220">
          <template slot="header" slot-scope="{}">
            <i style="color: #ff4949;margin-right: 4px;">*</i>
            <span>{{ $t('主体名称') }}</span>
          </template>
          <template slot-scope="scope">
            <el-form-item :prop="'dealSecuritiesPaymentPayers.' + scope.$index + '.investorId'" :rules="dealSecuritiesPaymentPayersRules.investorId">
              <el-select v-model="scope.row.investorId" :placeholder="mainBodyListOfCurrentProject.length <= 0 ? $t('请先添加主体') : $t('请选择')">
                <el-option
                  v-for="dict in mainBodyListOfCurrentProject"
                  :key="dict.investorId"
                  :label="$t(dict.investorName)"
                  :value="dict.investorId"
                />
              </el-select>
            </el-form-item>
          </template>
        </el-table-column>

        <el-table-column align="center" min-width="240">
          <template slot="header" slot-scope="{}">
            <i style="color: #ff4949;margin-right: 4px;">*</i>
            <span>{{ $t('付款金额') + $t('金额单位') }} {{ contractCurrencyText }}</span>
          </template>
          <template slot-scope="scope">
            <el-form-item :prop="'dealSecuritiesPaymentPayers.' + scope.$index + '.paymentAmount'" :rules="dealSecuritiesPaymentPayersRules.paymentAmount">
              <Money v-model="scope.row.paymentAmount" unit="w" />
            </el-form-item>
          </template>
        </el-table-column>

        <el-table-column align="center" min-width="240">
          <template slot="header" slot-scope="{}">
            <span>{{ $t('备注') }}</span>
          </template>
          <template slot-scope="scope">
            <el-form-item :prop="'dealSecuritiesPaymentPayers.' + scope.$index + '.remark'" :rules="dealSecuritiesPaymentPayersRules.remark">
              <el-input v-model="scope.row.remark" :placeholder="$t('备注')" show-word-limit maxlength="1000" />
            </el-form-item>
          </template>
        </el-table-column>

        <el-table-column v-if="!otherBtnHide" fixed="right" :label="$t('操作')" align="center" width="60px">
          <template slot-scope="scope">
            <el-button v-hasPermi="['deal:payment:remove']" size="small" type="text" icon="el-icon-delete" @click="delHandle(scope.$index, scope.row)" />
          </template>
        </el-table-column>
      </el-table>
      <div v-if="!otherBtnHide" class="tol">
        <el-button type="primary" icon="el-icon-plus" size="mini" @click="addPayment">{{ $t("添加") }}</el-button>
      </div>
      <FileTable :list.sync="form.fileList" has-permi="securities:payment" data-type="deal_securities_payment" :business-id="form.dealId" :btn-show="!otherBtnHide" />
    </el-form>
    <div slot="footer" class="dialog-footer" style="text-align: right;">
      <!--保存，保存并启动流程，取消 三个按钮-->
      <FormBtn ref="formBtn" :bus-data="form" has-permi="securities:payment" />
    </div>
    <!-- 收款方历史 -->
    <el-dialog :visible.sync="oaPayeeHistoryOpen" :title="$t('收款方历史')" :destroy-on-close="true" custom-class="folderOpen" style=" text-align: left;" append-to-body :close-on-click-modal="false" :lock-scroll="false" :closed="restaurants = loadAll()">
      <oaPayeeHistoryList ref="oaPayeeHistoryList" />
    </el-dialog>
  </div>
</template>

<script>
    import { saveDealSecuritiesPayment, getDealSecuritiesPayment, delDealSecuritiesPaymentPayer } from '@/api/deal/securities/payment/dealSecuritiesPayment'
    import { getPayeeHistory } from '@/api/oa/payment/oaPayment'
    import oaPayeeHistoryList from '@/views/oa/payment/oaPaymentHistoryList.vue'
    import { listDealInvestmentAll } from '@/api/deal/investment/dealInvestment.js'
    export default {
        components: {
          oaPayeeHistoryList
        },
        data() {
            return {
                // 表单参数
                form: {
                  dealSecuritiesPaymentPayers: []
                },
                // 当前项目主体列表
                mainBodyListOfCurrentProject: [],
                // 表单校验
                rules: {
                  actTitle: [{ required: true, message: this.$t('必填信息'),	trigger: 'blur' }],
                  applyUser: [{ required: true, message: this.$t('必填信息'),	trigger: 'blur' }],
                  applyTime: [{ required: true, message: this.$t('必填信息'),	trigger: 'blur' }],
                  total: [{ required: true, message: this.$t('必填信息'),	trigger: 'blur' }],
                  currency: [{ required: true, message: this.$t('必填信息'),	trigger: 'blur' }]
                },
                dealSecuritiesPaymentPayersRules: {
                  investorId: [{ required: true, message: this.$t('必填信息'),	trigger: 'blur' }],
                  paymentAmount: [{ required: true, message: this.$t('必填信息'),	trigger: 'blur' }]
                },
                // 遮罩层
                loading: false,
                // 操作按钮默认不展示
                buttonShow: true,
                oaPayeeHistoryOpen: false,
                // 是否隐藏其它按钮
                otherBtnHide: false
            }
        },
        created() {
            this.$bus.$emit('async_done')
        },
        methods: {
            // 初始化数据
            init(data) {
                this.loading = true
                // this.mainBodyListOfCurrentProject = []
                if (data != null && data.id !== undefined) {
                    getDealSecuritiesPayment(data.id).then(response => {
                        this.form = response.data
                        this.findListInvestor(this.form.dealId)
                        this.loading = false
                    }).catch(() => {
                        this.loading = false
                    })
                } else {
                    this.reset()
                    this.findListInvestor(this.$route.query.id)
                    this.loading = false
                }
            },
            // 加载主体列表
            findListInvestor(dealId) {
              // 加载项目主体都有哪些
              listDealInvestmentAll({ dealId: dealId }).then(response => {
                this.mainBodyListOfCurrentProject = response.data
              })
            },
            // 表单重置
            reset() {
                this.form = {
                    id: undefined,
                    dealId: this.$route.query.id,
                    actTitle: undefined,
                    applyUser: this.$store.state.user.userId,
                    applyTime: new Date(),
                    total: undefined,
                    currency: undefined,
                    payeeName: undefined,
                    depositBank: undefined,
                    accountTitle: undefined,
                    bankNumber: undefined,
                    addressReceiver: undefined,
                    actId: undefined,
                    actStatus: undefined,
                    remark: undefined,
                    createBy: undefined,
                    createTime: undefined,
                    updateBy: undefined,
                    updateTime: undefined,
                    delFlag: undefined
                }
                this.resetForm('form')
            },
            // 取消按钮
            cancel() {
                this.$parent.$parent.formOpen = false
                this.$parent.$parent.reset()
            },
            // 关闭form页面
            closeForm() {
                // 关闭form页面遮罩层
                this.loading = false
                // 关闭form页面
                if (this.$parent.$parent.formOpen !== undefined) {
                    this.$parent.$parent.formOpen = false
                }
                // 刷新list页面
                if (this.$parent.$parent.getList !== undefined) {
                  this.$parent.$parent.getList()
                }
            },
            /** 提交按钮 */
            submitForm(type) {
                return new Promise((resolve, reject) => {
                  this.$refs['form'].validate(valid => {
                    // 验证数据
                    if (valid) {
                      // 弹出遮罩层
                      this.loading = true
                      // 保存数据
                      saveDealSecuritiesPayment(this.form).then(response => {
                        if (response.code === 200) {
                          // 点击的按钮是保存并启动流程
                          if (type === 'process') {
                            // 启动流程
                            this.startProcess(response.data)
                            // 点击的仅保存
                          } else {
                            this.msgSuccess(this.$t('保存成功'))
                            // 关闭form页面
                            this.closeForm()
                          }
                          resolve()
                        } else {
                          this.msgError(response.msg)
                          this.loading = false
                          reject()
                        }
                      })
                    } else {
                      reject()
                      this.locationError(document)
                    }
                  })
                }).catch(() => {
                    this.loading = false
                })
           },
            // 启动流程
           startProcess(data) {
               this.loading = false
               // 启动流程时候传入的参数
               const processData = {}
               // 待办标题
               processData.title = data.actTitle
               // 业务表名
               processData.dataTable = 'deal_securities_payment'
               // 业务ID
               processData.dataId = data.id
               // 业务表单地址(待办页面需要打开的页面)
               processData.formPath = '@/views/deal/securities/payment/dealSecuritiesPaymentForm'
               // 菜单标识(根据菜单标识判断的走哪个流程)
               processData.menuKey = 'deal_securities_payment'
               this.startProcessByMenu(processData, () => {
                   this.form.actStatus = 'D'
                   this.msgSuccess(this.$t('数据保存成功,流程启动成功'))
                   this.closeForm()
               })
           },
          // -------------------------------------- 收款方空间控件方法 start(无需修改) --------------------------------------
          querySearch(queryString, cb) {
            var restaurants = this.restaurants
            var results = queryString ? restaurants.filter(this.createFilter(queryString)) : restaurants
            // 调用 callback 返回建议列表的数据
            cb(results)
          },
          createFilter(queryString) {
            return (restaurant) => {
              return (restaurant.value.toLowerCase().includes(queryString.toLowerCase()))
            }
          },
          // -------------------------------------- 收款方控件内置方法 end --------------------------------------
          // 收款方历史提示
          loadAll() {
            var temp = []
            getPayeeHistory().then(reponse => {
              for (var i = 0; i < reponse.data.length; i++) {
                var obj = {
                  'value': reponse.data[i].payeeName,
                  'address': reponse.data[i].depositBank + '|' + reponse.data[i].accountTitle + '|' + reponse.data[i].bankNumber
                }
                temp.push(obj)
              }
            })
            return temp
          },
          // 收款方选择后触发
          handleSelect(item) {
            this.form.payeeName = item.value
            var arr = item.address.split('|')
            this.form.depositBank = arr[0]
            this.form.accountTitle = arr[1]
            this.form.bankNumber = arr[2]
          },
          // 收款方旁边的小按钮
          handleIconClick() {
            this.oaPayeeHistoryOpen = true
          },
          // 添加付款主体
          addPayment() {
            const row = {
              id: undefined,
              investorId: undefined,
              paymentAmount: 0,
              remark: ''
            }
            if (!(this.form.dealSecuritiesPaymentPayers instanceof Array)) {
              this.$set(this.form, 'dealSecuritiesPaymentPayers', [])
            }
            this.$nextTick(() => {
              this.form.dealSecuritiesPaymentPayers.push(row)
            })
          },
          // 删除付款主体
          delHandle(index, row) {
            const id = row.id
            if (id !== undefined && id !== '' && id != null) {
              this.$confirm(this.$t('是否确认删除?'), this.$t('警告'), {
                confirmButtonText: this.$t('确定'),
                cancelButtonText: this.$t('取消'),
                type: 'warning'
              })
                .then(function() {
                  return delDealSecuritiesPaymentPayer(id)
                }).then(() => {
                this.form.dealSecuritiesPaymentPayers.splice(index, 1)
                return this.msgSuccess(this.$t('删除成功'))
              })
                .catch(function() {})
            } else {
              this.form.dealSecuritiesPaymentPayers.splice(index, 1)
            }
          },
          // 计算付款总额
          getSummaries() {
            let sum = 0
            this.form.dealSecuritiesPaymentPayers.forEach(item => {
              sum += +item.paymentAmount
            })
            this.$set(this.form, 'total', sum !== 0 ? sum : undefined)
            return sum
          }

        }

    }
</script>
